import jieba
import pymysql
from sklearn.preprocessing import MinMaxScaler
import numpy as np


def save_result(pipe, result):
    return pipe.process_item(result)



def run(id, content, w2vmodel, svclf):
    news_vec = [w2vmodel[content_item] for content_item in jieba.lcut(content) if content_item in w2vmodel.wv.vocab.keys()]
    mean_news_vec = np.array(news_vec).mean(axis=0)
    mean_news_vec = MinMaxScaler().fit_transform(np.array(mean_news_vec).reshape(1, -1))
    preds = svclf.predict(mean_news_vec)
    result = {}
    result['id'] = id
    result['content'] = content
    result['preds'] = preds[0]
    pipe = MysqlPipeline_MenHu()
    save_result(pipe, result)
    return id, preds


class MysqlPipeline_MenHu():  # 信息处理

    def __init__(self):  # 连接数据库data
        self.db = pymysql.connect(db='platform', host='localhost', port=3306, user='root', passwd='123',
                                  charset='utf8mb4')
        self.cursor = self.db.cursor()

    def process_item(self, item):  # 同步更新云端数据库
        if (item['id'] != '') & (item['preds'] != ''):
            sql = r"select * from yuqing_news_has_cla where news_id='" + str(item['id']) + "'"
            # print(sql)
            self.cursor.execute(sql)
            results = self.cursor.fetchall()
            if (results):  # 如果存在这条新闻，更新旧新闻
                work_sql = "update yuqing_news_has_cla set claid= '%s'" % (item['preds'])
                # print(work_sql)
                self.cursor.execute(work_sql)
                self.db.commit()
            else:  # 新增数据
                work_sql = "insert into yuqing_news_has_cla(news_id, claid) values('%s', '%s')" % (str(item['id']), item['preds'])
                # print(work_sql)
                self.cursor.execute(work_sql)
                self.db.commit()
        return True
